import requests

def download_image(url, ip):
    # 替换 URL 中的主机名为传入的 IP 地址
    # 假设 URL 的格式为 http://hostname/path/to/image
    if "://" in url:
        protocol, rest = url.split("://", 1)
    else:
        protocol, rest = "http", url

    # 提取路径
    path = rest.split("/", 1)[1] if "/" in rest else ""
    host = ip  # 使用传入的 IP 地址作为主机

    # 构造新的 URL
    # new_url = f"{protocol}://{host}/{path}"
    # print(new_url)
    new_url = url

    try:
        # 发送 GET 请求
        # response = requests.get(new_url, stream=True)
        response = request(new_url, ip)
        response.raise_for_status()  # 检查请求是否成功

        # 获取文件名
        filename = url.split("/")[-1]  # 从原 URL 中提取文件名

        # 下载图像并保存
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)

        print(f"Image downloaded successfully: {filename}")

    except requests.exceptions.RequestException as e:
        print(f"Error downloading image: {e}")

if __name__ == "__main__":
    # 用户输入 URL 和 IP 地址
    # user_url = input("Enter the image URL: ")
    # user_ip = input("Enter the IP address: ")

    user_url = "https://wx4.sinaimg.cn/mw690/007StLOugy1hzeawvwn90j30dw0ep3zs.jpg"
    user_ip = "156.225.108.43"

    download_image(user_url, user_ip)